﻿using System;
using System.Collections.Generic;
using System.Linq;
using StockFinder.Model;
using StockFinder.Model.Constants;

namespace StockFinder.Indicators.Day.Volume
{
    public class SimpleMovingAveragePercentOfDailyVolumeDayIndicator : BaseDayIndicator
    {
        public SimpleMovingAveragePercentOfDailyVolumeDayIndicator(int lookbackPeriod, string indicatorName)
            : base(lookbackPeriod, indicatorName)
        {
        }

        public override void ApplyIndicator(List<DailyPrice> prices)
        {
            if (!Initialize(prices)) return;

            var orderedPrices = prices.OrderBy(p => p.PriceDate);
            DailyPrice currentPrice;

            var pricesArray = orderedPrices.ToArray();
            IEnumerable<DailyPrice> skippedPrices;
            IEnumerable<DailyPrice> takenPrices;

            var pricesCount = orderedPrices.Count();            
            
            for (var i = (LookbackPeriod - 1); i < pricesCount; i++)
            {
                currentPrice = pricesArray[i];

                var numberToSkip = (i + 1) - LookbackPeriod;

                skippedPrices = pricesArray.Skip(numberToSkip);

                takenPrices = skippedPrices.Take(LookbackPeriod);

                var currentAverage = Math.Round(takenPrices.Average(p => p.Volume), 0);

                if (currentPrice.Volume > 0)
                {
                    currentPrice.DayIndicators[IndicatorName] = Math.Round(((currentPrice.Volume - currentAverage) / currentAverage) * 100, 2);
                }                
            }
        }

        #region Common Indicators
        public static readonly SimpleMovingAverageDailyVolumeDayIndicator Month = new SimpleMovingAverageDailyVolumeDayIndicator(22, DayIndicatorNames.VOLUME_SMA_MONTH); //avg 22 days in a month       
        public static readonly SimpleMovingAverageDailyVolumeDayIndicator Quarter = new SimpleMovingAverageDailyVolumeDayIndicator(65, DayIndicatorNames.VOLUME_SMA_QUARTER); //avg 65 days in a quarter       
        #endregion
    }
}
